/**
 * \file Log.h
 * \brief Kernel logging facilities
 * \author Corey Tabaka
 */

/*
   Copyright 2006 Corey Tabaka

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include <Log.h>
#include <Sync.h>
#include <stdio.h>
#include <stdarg.h>

#include <i386/console.h>

static int logLevel = LOG_LOW;

static WriteString console = (WriteString) cputs;

static InterruptLock lock;

void Log::initialize(void) {
}

void Log::setLevel(int level) {
	lock.lock();
	
	if (level >= LOG_CRITICAL && level <= LOG_LOW) {
		logLevel = level;
	}
	
	lock.unlock();
}

int Log::getLevel(void) {
	return logLevel;
}

void Log::setConsole(WriteString cons) {
	lock.lock();
	
	console = cons;
	
	lock.unlock();
}

int Log::printf(int level, const char *fmt, ...) {
	lock.lock();
	
	int result = 0;
	
	if (level <= logLevel) {
		va_list parms;
		char buf[2*1024];
	
	    va_start(parms,fmt);
	    
	    result = vsprintf(buf, (char *) fmt, parms);
	    if (console) {
	    	console(buf);
	    } else {
	    	cputs(buf);
	    }
	    
	    va_end(parms);
	}
	
	lock.unlock();
	return result;
}

void Log::hexdump(int level, const uint8 *buffer, uint32 len, bool le) {
	if (le) {
		Log::printf(level, "           F  E  D  C  B  A  9  8  7  6  5  4  3  2  1  0");
	} else {
		Log::printf(level, "           0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F");
	}
	
	uint32 alen = le ? (len + 0x0f) & ~0x0f : len;
	for (uint32 i=0; i < alen; i++) {
		uint32 index = i & 0x0f;
		
		if (index == 0) {
		 	Log::printf(level, "\n%07x0h", i >> 4);
		}
		
		if (le) {
			uint32 offset = i & ~0x0f;
			uint32 rindex = 16 - (index + 1);
			
			if (rindex + offset >= len) {
				Log::printf(level, "   ");
			} else {
				Log::printf(level, " %02x", buffer[rindex + offset]);
			}
		} else {
			Log::printf(level, " %02x", buffer[i]);
		}
	}
	
	Log::printf(level, "\n");
}
